<template>
  <div class="role-management-container">
    <div class="page-header">
      <h2 class="page-title">角色管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleCreateRole">
          <el-icon><Plus /></el-icon>新建角色
        </el-button>
        <el-button @click="handleRefresh">
          <el-icon><Refresh /></el-icon>刷新
        </el-button>
      </div>
    </div>
    
    <!-- 搜索过滤器 -->
    <div class="filter-container">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="角色名称">
          <el-input v-model="filterForm.name" placeholder="请输入角色名称" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filterForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 角色表格 -->
    <div class="role-table">
      <el-table
        :data="displayRoleList"
        style="width: 100%"
        v-loading="tableLoading"
        border
      >
        <el-table-column type="index" width="50" />
        <el-table-column prop="name" label="角色名称" min-width="150" />
        <el-table-column prop="code" label="角色编码" min-width="150" />
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="230">
          <template #default="scope">
            <el-button size="small" @click="handleEditRole(scope.row)">编辑</el-button>
            <el-button 
              size="small" 
              :type="scope.row.status === 1 ? 'warning' : 'success'"
              @click="handleToggleStatus(scope.row)"
              :disabled="scope.row.code === 'SUPER_ADMIN' && scope.row.status === 1"
            >
              {{ scope.row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button 
              size="small" 
              type="info"
              @click="handlePermissions(scope.row)"
            >
              权限设置
            </el-button>
            <el-button 
              size="small" 
              type="danger"
              @click="handleDeleteRole(scope.row)"
              :disabled="scope.row.code === 'SUPER_ADMIN'"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:currentPage="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    
    <!-- 新建/编辑角色对话框 -->
    <el-dialog
      v-model="roleDialog.visible"
      :title="roleDialog.isEdit ? '编辑角色' : '新建角色'"
      width="600px"
    >
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="roleRules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色编码" prop="code">
          <el-input 
            v-model="roleForm.code" 
            placeholder="请输入角色编码，如ADMIN、USER等" 
            :disabled="roleDialog.isEdit"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="roleForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入角色描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="roleDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="submitRoleForm">确定</el-button>
      </template>
    </el-dialog>
    
    <!-- 权限设置对话框 -->
    <el-dialog
      v-model="permissionDialog.visible"
      title="权限设置"
      width="600px"
    >
      <div v-if="permissionDialog.roleName" class="permission-title">
        为 <strong>{{ permissionDialog.roleName }}</strong> 设置权限
      </div>
      <el-tree
        ref="permissionTreeRef"
        :data="permissionTree"
        show-checkbox
        node-key="id"
        :default-checked-keys="permissionDialog.selectedPermissions"
        :props="{ label: 'name', children: 'children' }"
      />
      <template #footer>
        <el-button @click="permissionDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="savePermissions">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, nextTick, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh, Search } from '@element-plus/icons-vue'

export default {
  name: 'RoleManagement',
  components: {
    Plus,
    Refresh,
    Search
  },
  setup() {
    // 模拟角色数据
    const mockRoles = [
      {
        id: 1,
        name: '超级管理员',
        code: 'SUPER_ADMIN',
        description: '系统超级管理员，拥有所有权限',
        status: 1,
        permissions: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
        createTime: '2023-01-01 00:00:00'
      },
      {
        id: 2,
        name: '管理员',
        code: 'ADMIN',
        description: '系统管理员，负责日常系统管理',
        status: 1,
        permissions: [1, 2, 3, 5, 6, 7, 9, 10, 13],
        createTime: '2023-01-02 10:30:00'
      },
      {
        id: 3,
        name: '窗口操作员',
        code: 'OPERATOR',
        description: '负责窗口日常业务操作',
        status: 1,
        permissions: [1, 5, 9, 10],
        createTime: '2023-01-03 14:20:00'
      },
      {
        id: 4,
        name: '统计分析员',
        code: 'ANALYST',
        description: '负责统计分析业务数据',
        status: 1,
        permissions: [1, 13, 14, 15],
        createTime: '2023-01-04 16:45:00'
      },
      {
        id: 5,
        name: '临时角色',
        code: 'TEMP',
        description: '临时权限角色',
        status: 0,
        permissions: [1],
        createTime: '2023-01-05 09:10:00'
      }
    ]
    
    // 模拟权限树数据
    const permissionTree = [
      {
        id: 1,
        name: '系统首页',
        children: []
      },
      {
        id: 2,
        name: '系统管理',
        children: [
          {
            id: 3,
            name: '用户管理',
            children: [
              {
                id: 4,
                name: '用户管理-新增/编辑'
              }
            ]
          },
          {
            id: 5,
            name: '角色管理',
            children: [
              {
                id: 6,
                name: '角色管理-新增/编辑'
              },
              {
                id: 7,
                name: '角色管理-权限分配'
              },
              {
                id: 8,
                name: '角色管理-删除'
              }
            ]
          }
        ]
      },
      {
        id: 9,
        name: '窗口管理',
        children: [
          {
            id: 10,
            name: '窗口管理-新增/编辑'
          },
          {
            id: 11,
            name: '窗口管理-删除'
          },
          {
            id: 12,
            name: '窗口管理-业务分配'
          }
        ]
      },
      {
        id: 13,
        name: '统计分析',
        children: [
          {
            id: 14,
            name: '业务统计'
          },
          {
            id: 15,
            name: '窗口效率分析'
          }
        ]
      }
    ]
    
    // 角色列表数据
    const roleList = ref([...mockRoles])
    const tableLoading = ref(false)
    
    // 分页信息
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: mockRoles.length
    })
    
    // 过滤表单
    const filterForm = reactive({
      name: '',
      status: ''
    })
    
    // 角色对话框
    const roleDialog = reactive({
      visible: false,
      isEdit: false
    })
    
    // 权限设置对话框
    const permissionDialog = reactive({
      visible: false,
      roleId: null,
      roleName: '',
      selectedPermissions: []
    })
    
    // 角色表单
    const roleFormRef = ref(null)
    const roleForm = reactive({
      id: null,
      name: '',
      code: '',
      description: '',
      status: 1
    })
    
    // 权限树引用
    const permissionTreeRef = ref(null)
    
    // 表单验证规则
    const roleRules = {
      name: [
        { required: true, message: '请输入角色名称', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
      ],
      code: [
        { required: true, message: '请输入角色编码', trigger: 'blur' },
        { pattern: /^[A-Z][A-Z_]*$/, message: '编码必须为大写字母和下划线，以字母开头', trigger: 'blur' }
      ]
    }
    
    // 根据筛选条件和分页显示角色列表
    const displayRoleList = computed(() => {
      // 应用筛选条件
      let filteredList = roleList.value.filter(item => {
        let nameMatch = true, statusMatch = true
        
        if (filterForm.name) {
          nameMatch = item.name.includes(filterForm.name)
        }
        
        if (filterForm.status !== '') {
          statusMatch = item.status === filterForm.status
        }
        
        return nameMatch && statusMatch
      })
      
      // 应用分页
      const start = (pagination.currentPage - 1) * pagination.pageSize
      const end = start + pagination.pageSize
      
      return filteredList.slice(start, end)
    })
    
    // 监听筛选列表变化更新总数
    const updatePaginationTotal = () => {
      const filteredList = roleList.value.filter(item => {
        let nameMatch = true, statusMatch = true
        
        if (filterForm.name) {
          nameMatch = item.name.includes(filterForm.name)
        }
        
        if (filterForm.status !== '') {
          statusMatch = item.status === filterForm.status
        }
        
        return nameMatch && statusMatch
      })
      
      pagination.total = filteredList.length
    }
    
    // 监听过滤条件变化
    watch([() => filterForm.name, () => filterForm.status], () => {
      updatePaginationTotal()
    })
    
    // 监听角色列表变化
    watch(roleList, () => {
      updatePaginationTotal()
    }, { deep: true })
    
    // 处理搜索
    const handleSearch = () => {
      pagination.currentPage = 1
    }
    
    // 重置过滤器
    const resetFilter = () => {
      Object.keys(filterForm).forEach(key => {
        filterForm[key] = ''
      })
      pagination.currentPage = 1
    }
    
    // 处理页面大小变化
    const handleSizeChange = (size) => {
      pagination.pageSize = size
    }
    
    // 处理页码变化
    const handleCurrentChange = (page) => {
      pagination.currentPage = page
    }
    
    // 处理刷新
    const handleRefresh = () => {
      tableLoading.value = true
      setTimeout(() => {
        tableLoading.value = false
        ElMessage.success('刷新成功')
      }, 500)
    }
    
    // 处理新建角色
    const handleCreateRole = () => {
      roleDialog.isEdit = false
      roleDialog.visible = true
      
      Object.keys(roleForm).forEach(key => {
        if (key === 'status') {
          roleForm[key] = 1
        } else {
          roleForm[key] = ''
        }
      })
    }
    
    // 处理编辑角色
    const handleEditRole = (row) => {
      roleDialog.isEdit = true
      roleDialog.visible = true
      
      roleForm.id = row.id
      roleForm.name = row.name
      roleForm.code = row.code
      roleForm.description = row.description
      roleForm.status = row.status
    }
    
    // 处理删除角色
    const handleDeleteRole = (row) => {
      if (row.code === 'SUPER_ADMIN') {
        ElMessage.warning('超级管理员角色不允许删除')
        return
      }
      
      ElMessageBox.confirm(`确定要删除角色"${row.name}"吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 在模拟数据中删除对应角色
        const index = roleList.value.findIndex(item => item.id === row.id)
        if (index !== -1) {
          roleList.value.splice(index, 1)
          ElMessage.success('删除角色成功')
        }
      }).catch(() => {})
    }
    
    // 处理切换状态
    const handleToggleStatus = (row) => {
      if (row.code === 'SUPER_ADMIN' && row.status === 1) {
        ElMessage.warning('超级管理员角色不允许禁用')
        return
      }
      
      const newStatus = row.status === 1 ? 0 : 1
      const statusText = newStatus === 1 ? '启用' : '禁用'
      
      ElMessageBox.confirm(`确定要${statusText}角色"${row.name}"吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 在模拟数据中更新状态
        const index = roleList.value.findIndex(item => item.id === row.id)
        if (index !== -1) {
          roleList.value[index].status = newStatus
          ElMessage.success(`${statusText}角色成功`)
        }
      }).catch(() => {})
    }
    
    // 处理权限设置
    const handlePermissions = (row) => {
      permissionDialog.roleId = row.id
      permissionDialog.roleName = row.name
      
      // 找到角色对应的权限
      const role = roleList.value.find(item => item.id === row.id)
      permissionDialog.selectedPermissions = role ? [...role.permissions] : []
      
      permissionDialog.visible = true
      
      // 确保树渲染完成后才设置选中状态
      nextTick(() => {
        if (permissionTreeRef.value) {
          permissionTreeRef.value.setCheckedKeys(permissionDialog.selectedPermissions)
        }
      })
    }
    
    // 保存权限设置
    const savePermissions = () => {
      if (!permissionDialog.roleId) return
      
      // 获取选中的权限ID
      const checkedKeys = permissionTreeRef.value.getCheckedKeys()
      const halfCheckedKeys = permissionTreeRef.value.getHalfCheckedKeys()
      const allCheckedKeys = [...checkedKeys, ...halfCheckedKeys]
      
      // 更新角色的权限
      const index = roleList.value.findIndex(item => item.id === permissionDialog.roleId)
      if (index !== -1) {
        roleList.value[index].permissions = allCheckedKeys
        ElMessage.success('权限设置成功')
        permissionDialog.visible = false
      }
    }
    
    // 提交角色表单
    const submitRoleForm = () => {
      roleFormRef.value.validate((valid) => {
        if (valid) {
          const isEdit = roleDialog.isEdit
          
          if (isEdit) {
            // 编辑现有角色
            const index = roleList.value.findIndex(item => item.id === roleForm.id)
            if (index !== -1) {
              roleList.value[index] = {
                ...roleList.value[index],
                name: roleForm.name,
                description: roleForm.description,
                status: roleForm.status,
              }
              ElMessage.success('更新角色成功')
            }
          } else {
            // 检查角色编码是否已存在
            const existingCode = roleList.value.find(item => item.code === roleForm.code)
            if (existingCode) {
              ElMessage.error('角色编码已存在')
              return
            }
            
            // 创建新角色
            const newId = Math.max(...roleList.value.map(item => item.id), 0) + 1
            const now = new Date()
            const createTime = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`
            
            roleList.value.push({
              id: newId,
              name: roleForm.name,
              code: roleForm.code,
              description: roleForm.description,
              status: roleForm.status,
              permissions: [],
              createTime: createTime
            })
            ElMessage.success('创建角色成功')
          }
          
          roleDialog.visible = false
        }
      })
    }
    
    onMounted(() => {
      // 初始化时不需要额外操作，模拟数据已加载
    })
    
    return {
      displayRoleList,
      tableLoading,
      pagination,
      filterForm,
      roleDialog,
      roleFormRef,
      roleForm,
      roleRules,
      permissionDialog,
      permissionTree,
      permissionTreeRef,
      handleSearch,
      resetFilter,
      handleSizeChange,
      handleCurrentChange,
      handleRefresh,
      handleCreateRole,
      handleEditRole,
      handleDeleteRole,
      handleToggleStatus,
      handlePermissions,
      savePermissions,
      submitRoleForm
    }
  }
}
</script>

<style scoped>
.role-management-container {
  padding: 15px 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 22px;
  font-weight: 500;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.filter-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.04);
}

.role-table {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.04);
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.permission-title {
  margin-bottom: 15px;
  font-size: 16px;
  color: #606266;
}
</style> 